package copyengine.resource.file
{
	import copyengine.resource.dto.ResInitDTO;
	import copyengine.resource.dto.ResObjectRequestParamDTO;
	import copyengine.utils.GeneralUtils;

	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.ProgressEvent;
	import flash.net.URLLoader;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequest;
	import flash.utils.ByteArray;

	public class CEXmlResourceFile extends CEBasicResFile
	{
		private var xmlFileLoader:URLLoader;
		private var xmlFile:XML;
		private var resFilePath:String;

		public function CEXmlResourceFile()
		{
			super();
		}

		override protected function doInitialize(_resInitDTO:ResInitDTO):void
		{
			resFilePath = _resInitDTO.filePath;
		}

		override public function getObject(_dto:ResObjectRequestParamDTO):Object
		{
			return xmlFile;
		}

		override protected function doStartLoadFile():void
		{
			xmlFileLoader = new URLLoader();
			xmlFileLoader.load(new URLRequest(resFilePath));
			xmlFileLoader.dataFormat = URLLoaderDataFormat.BINARY;
			GeneralUtils.addTargetEventListener(xmlFileLoader, Event.COMPLETE, onLoaded);
			GeneralUtils.addTargetEventListener(xmlFileLoader, ProgressEvent.PROGRESS, loadFileOnProgress);
			GeneralUtils.addTargetEventListener(xmlFileLoader, IOErrorEvent.IO_ERROR, loadFileOnError, false, 0, true);
		}

		override protected function releaseLoader():void
		{
			xmlFileLoader.close();
			GeneralUtils.removeTargetEventListener(xmlFileLoader, Event.COMPLETE, onLoaded);
			GeneralUtils.removeTargetEventListener(xmlFileLoader, ProgressEvent.PROGRESS, loadFileOnProgress);
			GeneralUtils.removeTargetEventListener(xmlFileLoader, IOErrorEvent.IO_ERROR, loadFileOnError);
			xmlFileLoader = null;
		}

		private function onLoaded(e:Event):void
		{
			var byteArray:ByteArray = xmlFileLoader.data as ByteArray;
			byteArray.uncompress();
			xmlFile = new XML(byteArray);
			releaseLoader();
			loadFileComplate();
		}

	}
}
